package com.example.mybaseapp.ui

import android.content.ContentResolver
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.mybaseapp.R
import java.io.File
import java.io.FileOutputStream

/**
 * Android11之上，文件选择器获取文件路径
 * 思路：
 */
class QFileSelectActivity : AppCompatActivity() {
    companion object {
        const val Q_SELECT_FILE_CODE = 3336 //选择文件
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_qfile_select)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun showSelect() {
//        使用这种方式， 只支持选择文档（即图片、音视频、文件 等）
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)

//        不单只支持文件/图片，还支持选择通讯录、录音、音频、视频等内容
//        val intent = Intent(Intent.ACTION_GET_CONTENT)
//        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "*/*" // 所有文件类型
        // 支持多选（长按多选）
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)

        startActivityForResult(intent, Q_SELECT_FILE_CODE)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                Q_SELECT_FILE_CODE -> {
// 多选的情况
                    val clipData = data?.clipData
                    if (clipData != null && clipData.itemCount > 0) {
                        for (i in 0 until clipData.itemCount) {
                            val item = clipData.getItemAt(i)
                            val uri = item.uri ?: continue
                            var  pathList  = queryUri(uri)
                            Log.d("Fire", "onActivityResult: mutil file ${uri.path} $pathList")
//                            var path = pathList
//                            var nameList = path.split("/")
//                            var name = nameList[nameList.size -1]
//                            fileTransmissionStateDataList.add(FileTransmissionStateData(pathList,0, name, System.currentTimeMillis()))
                        }
                    }
                    // 单选的情况
                    data?.data?.let { uri ->
                        var  pathList  = queryUri(uri)
                        Log.d("Fire", "onActivityResult: ${uri.path} $pathList")
//                        var path = pathList
//                        var nameList = path.split("/")
//                        var name = nameList[nameList.size -1]
//                        fileTransmissionStateDataList.add(FileTransmissionStateData(pathList,0, name, System.currentTimeMillis()))

                    }
                }

            }
        }
    }

    private fun queryUri(uri:Uri):String{
        val contentResolver = applicationContext.contentResolver
        val cursor = contentResolver.query(uri, null, null, null, null)
        Log.d("Fire", "queryUri: $uri \n path:${uri.path} \n pathSegments:${uri.pathSegments}")
        val openFileDescriptor = contentResolver.openFileDescriptor(uri, "r")
        val toString = openFileDescriptor?.fileDescriptor.toString()
        Log.d("Fire", "queryUri: $toString")

        cursor.use {
            if (it != null && it.moveToFirst()) {
                val filenameIndex = it.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
                var displayName:String?=null
                while (!it.isAfterLast) {
                    if(filenameIndex>=0) {
                        displayName = it.getString(filenameIndex)//获取文件名和后缀
                    }
                    it.getColumnIndex(MediaStore.Images.ImageColumns.DATA).also { it2->
                        if(it2>0){
                            Log.d("Fire", "queryUri: ${it.getString(it2)}")
                        }
                    }
                    // 对获取的文件名和路径进行处理
                    Log.d("File Details", "Name: ${displayName?:""} ")
                    it.moveToNext()
                }
                displayName?.let {it1->
                    val pair = splitFileNameAndExtension(it1)
                    return getRealPathFromURI(contentResolver, uri, pair.first,pair.second)
                }
            }
        }
        return ""
    }

    /**
     * 根据文件名拆分文件名和后缀
     */
    fun splitFileNameAndExtension(fileName: String): Pair<String, String> {
        val lastDotIndex = fileName.lastIndexOf(".")

        return if (lastDotIndex > 0 && lastDotIndex < fileName.length - 1) {
            val name = fileName.substring(0, lastDotIndex)
            val extension = fileName.substring(lastDotIndex)
            Pair(name, extension)
        } else {
            Pair(fileName, "") // 如果没有后缀，返回空字符串
        }
    }

    fun getRealPathFromURI(contentResolver: ContentResolver, uri: Uri, fileName:String, fileExtension:String): String {
        var realPath = ""
        try {
            contentResolver.openInputStream(uri)?.use { inputStream ->
                val file = File.createTempFile(fileName, fileExtension)
                val outputStream = FileOutputStream(file)
                inputStream.copyTo(outputStream)
                realPath = file.absolutePath
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return realPath
    }
}